<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="操作时间">
          <el-date-picker
            v-model="dateRange"
            style="width: 240px"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="日志编号" prop="id">
          <el-input
            v-model="queryParams.id"
            placeholder="日志编号"
            @keyup.enter="handleQuery"
            class="input-inner"
          />
        </el-form-item>


        <el-form-item label="操作结果" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="全部"
            clearable
            class="!w-[100px]"
          >
            <el-option :value="0" label="成功"/>
            <el-option :value="1" label="失败"/>
          </el-select>
        </el-form-item>
        <el-form-item label="模块" prop="module">
          <el-select
            v-model="queryParams.module"
            placeholder="全部"
            clearable
            class="!w-[100px]"
          >
            <el-option v-for="module in moduleOptions"
                       :key="module.value"
                       :label="module.label"
                       :value="module.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="业务类型" prop="businessType">
          <el-select
            v-model="queryParams.businessType"
            placeholder="全部"
            clearable
            class="!w-[100px]"
          >
            <el-option v-for="bizType in bizTypeOptions"
                       :key="bizType.value"
                       :label="bizType.label"
                       :value="bizType.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="操作人" prop="createBy">
          <el-input
            v-model="queryParams.createBy"
            placeholder="操作人"
            @keyup.enter="handleQuery"
            class="input-inner"
          />
        </el-form-item>

        <el-form-item>
          <el-button class="filter-item" type="primary" @click="handleQuery">
            <i-ep-search/>
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <i-ep-refresh/>
            重置
          </el-button>

          <el-button class="ml-3" @click="handleExport">
            <template #icon>
              <i-ep-download/>
            </template>
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">

      <el-table
        v-loading="loading"
        :data="logList"
        row-key="id"
        height="calc(100vh - 290px)"
      >
        <el-table-column prop="id" label="日志编号" :min-width="90"/>
        <el-table-column prop="module" label="模块" :formatter="moduleFormatter" :min-width="100">
        </el-table-column>
        <el-table-column prop="title" label="标题" align="center" :min-width="300"/>
        <el-table-column prop="businessType" label="业务类型" :min-width="100"/>
        <el-table-column label="操作结果" :min-width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0" type="success">成功</el-tag>
            <el-tag v-else type="danger">失败</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="operName" label="操作人" :min-width="100"/>
        <el-table-column prop="operTime" label="操作时间" align="center" :min-width="200"/>
        <el-table-column prop="costTime" label="执行时长" :formatter="costTimeFormatter" align="right" :min-width="100"/>

        <el-table-column label="操作" align="center" fixed="right" :min-width="100">
          <template #default="scope">
            <el-button
              v-hasPerm="['sys:operlog:detail']"
              size="small"
              type="text"
              @click.stop="handleView(scope.row)">
              <el-icon>
                <View/>
              </el-icon>
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 操作日志详细 -->
    <el-dialog title="操作日志详细" v-model="open" width="900px" append-to-body>
      <el-form
        ref="operLogFormRef"
        :model="form"
        label-width="100px"
        size="default"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="操作模块：">{{ moduleFormatter(form) }}/{{ form.businessType }}/{{ form.title }}</el-form-item>
            <el-form-item label="登录信息：">{{ form.operName }} / {{ form.operIp }} / {{ form.operLocation }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请求地址：">{{ form.operUrl }}</el-form-item>
            <el-form-item label="请求方式：">{{ form.requestMethod }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="操作方法：">{{ form.method }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="请求参数：">
              <div class="wrap-text" style="{ word-break: break-all; white-space: pre-wrap; }">
                {{ form.operParam }}
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="返回参数：">
              <div class="wrap-text" style="{ word-break: break-all; white-space: pre-wrap; }">
                {{ form.jsonResult }}
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="操作状态：">
              <div v-if="form.status === 0">正常</div>
              <div v-else-if="form.status === 1">失败</div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="消耗时间：">{{ form.costTime }}ms</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="操作时间：">{{ form.operTime }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="异常信息：" v-if="form.status === 1">{{ form.errorMsg }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" align="right">
        <el-button @click="open = false">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import {exportLog, listLogs} from "@/api/log/oper";
import {getBizTypeSelection, getModuleSelection} from "@/api/common";

import {OperLogQuery, OperLogVO} from "@/api/log/oper/types";

defineOptions({
  name: "OperLog",
  inheritAttrs: false
});

const queryFormRef = ref(ElForm);
const operLogFormRef = ref(ElForm);
const loading = ref(false);

const total = ref(0)
const dateRange = ref('')

const queryParams = reactive<OperLogQuery>({
  pageNum: 1,
  pageSize: 10,
});

const logList = ref<OperLogVO[]>();

const moduleOptions = ref<OptionType[]>();
const bizTypeOptions = ref<OptionType[]>();

const open = ref(false);

// 表单参数
let form = reactive<OperLogVO>({});

/** 查询 */
function handleQuery() {
  loading.value = true;
  listLogs(queryParams)
    .then(({data}) => {
      logList.value = data.list;
      total.value = parseInt(data.total);
    })
    .finally(() => {
      loading.value = false;
    });
}

/**重置查询 */
function resetQuery() {
  queryParams.pageNum = 1;
  dateRange.value = "";
  queryParams.beginTime = ''
  queryParams.endTime = ''
  queryFormRef.value.resetFields();
  handleQuery();
}


function loadModuleOptions() {
  getModuleSelection().then(({data}) => {
    moduleOptions.value = data
  });
}

function loadBizTypeOptions() {
  getBizTypeSelection().then(({data}) => {
    bizTypeOptions.value = data
  });
}

/** 详细按钮操作 */
function handleView(row: any) {
  open.value = true;
  form = row;
  console.log("查看详情", form)
}

function moduleFormatter(row: OperLogVO) {
  const module = moduleOptions.value?.find(item => item.value === row.module);
  return module?.label;
}

function costTimeFormatter(row: OperLogVO) {
  return row.costTime + " ms";
}

function handleExport() {
  console.log('导出')
  exportLog(queryParams).then((response: any) => {
    const fileData = response.data;
    const fileName = decodeURI(
      response.headers["content-disposition"].split(";")[1].split("=")[1]
    );
    const fileType =
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

    const blob = new Blob([fileData], {type: fileType});
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement("a");
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  });
}

onMounted(() => {
  handleQuery();
  loadModuleOptions();
  loadBizTypeOptions();
});

watch(dateRange, (newVal) => {
  console.log(newVal)
  if (newVal) {
    queryParams.beginTime = newVal[0] + " 00:00:00";
    queryParams.endTime = newVal[1] + " 23:59:59";
  }
});
</script>

<style scoped>
.input-inner {
  width: 100px;
}

.wrap-text {
  /* 如果 scoped 样式不能穿透到 el-form-item 内部，可以尝试使用深度选择器 */
  overflow-wrap: break-word;
  word-wrap: break-word; /* Internet Explorer 5.5+ & legacy browsers */
  word-break: break-all;
  white-space: pre-wrap;
}
</style>
